﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;
using System.Data.Entity;
using Top.Api.Response;
using AscentExplorer.Models;
using Top.Api.Domain;

namespace AscentExplorer.Services
{

    public sealed class ItemSaveActivity : CodeActivity
    {
        // Define an activity input argument of type string
        public InArgument<ItemGetResponse> Response { get; set; }

        // If your activity returns a value, derive from CodeActivity<TResult>
        // and return the value from the Execute method.
        protected override void Execute(CodeActivityContext context)
        {
            // Obtain the runtime value of the Text input argument
            ItemGetResponse response = context.GetValue(this.Response);
            if (response != null)
            {
                using (TopContext db = new TopContext())
                {
                    Item item = response.Item;
                    if (db.Items.Any(i => i.NumIid == item.NumIid))
                    {
                        int dbId = db.Items.First(i => i.NumIid == item.NumIid).DbId;
                        item = db.Items.Find(dbId);
                        item.DbId = dbId;

                        db.Items.Attach(item);
                        db.Entry(item).State = System.Data.EntityState.Modified;
                    }
                    else
                    {
                        db.Items.Add(item);
                        //db.Entry(item).State = System.Data.EntityState.Added;
                    }

                    int recordsAffected = db.SaveChanges();
                    Console.WriteLine("追加{0}记录成功", recordsAffected);
                }
            }
        }
    }
}
